/*
 * Tint Browser for Android
 * 
 * Copyright (C) 2012 - to infinity and beyond J. Devauchelle and contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

package com.cnbrowser.android.ui.fragments.homepage;

import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.cnbrowser.android.R;
import com.cnbrowser.android.ui.cbrowser.StartPageItemClickedListener;
import com.cnbrowser.android.ui.cbrowser.Website;
import com.cnbrowser.android.ui.cbrowser.WebsiteAdapter;

public class LeftFragment extends Fragment {
    private static final String TAG = "LeftFragment";

    private View thisView;
    private StartPageItemClickedListener startPageItemClickedListener;

    Website[] websites;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        thisView = inflater.inflate(R.layout.cb_start_page_left_fragment, container, false);
        if (thisView == null) return thisView;

        GridView gridView = (GridView) thisView.findViewById(R.id.gridView);

        makeWebsites();

        gridView.setAdapter(new WebsiteAdapter(gridView.getContext(), R.layout.cb_start_page_left_fragment_item, websites));
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String value = (String) (view.getTag());
                startPageItemClickedListener.onItemClicked(value);
            }
        });

        return thisView;
    }

    private void makeWebsites() {
        String[] websiteNames = getResources().getStringArray(R.array.websiteNames);
        String[] websiteUrls = getResources().getStringArray(R.array.websiteUrls);
        TypedArray websiteIcons = getResources().obtainTypedArray(R.array.websiteIcons);
        websites = new Website[websiteNames.length];
        for (int i = 0; i < websiteNames.length; i++) {
            websites[i] = new Website(websiteNames[i], websiteIcons.getResourceId(i, -1), websiteUrls[i]);
        }
    }

    public void setOnStartPageItemClickedListener(StartPageItemClickedListener startPageItemClickedListener) {
        this.startPageItemClickedListener = startPageItemClickedListener;
    }
}
